package com.xgk.boot.module.core.service.user;


import com.xgk.boot.framework.common.constant.ErrorCodeConstants;
import com.xgk.boot.framework.common.enums.CommonStatusEnum;
import com.xgk.boot.module.core.dal.entity.customer.CustomerDO;
import com.xgk.boot.module.core.dal.entity.user.AdminUserDO;
import com.xgk.boot.module.core.dal.iservice.UserRoleService;
import com.xgk.boot.module.core.service.customer.CustomerServiceImpl;
import com.xgk.boot.module.core.service.permission.UserRoleServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.xgk.boot.framework.common.constant.ErrorCodeConstants.USER_NOT_EXISTS;
import static com.xgk.boot.framework.common.exception.util.ServiceExceptionUtil.exception;

@Service
public class UserServiceImpl {


    @Resource
    private CustomerServiceImpl customerService;
    @Resource
    private AdminUserService adminUserService;
    @Autowired
    private UserRoleServiceImpl userRoleService;

    public Boolean updateUserStatus(Long id) {
        AdminUserDO user = adminUserService.getUser(id);
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }
        if(CommonStatusEnum.ENABLE.getStatus().equals(user.getStatus())) {
            CustomerDO custCacheByCode = customerService.getCustCacheByCode(user.getUsername());
            if(custCacheByCode != null && custCacheByCode.getCustomerStatus().equals(CommonStatusEnum.ENABLE.getStatus())) {
                throw exception(ErrorCodeConstants.USER_CUSTOMER_STATUS_ENABLE);
            }
            user.setStatus(CommonStatusEnum.DISABLE.getStatus());
        }else {
            user.setStatus(CommonStatusEnum.ENABLE.getStatus());
        }
        adminUserService.updateUserStatus(id,user.getStatus());
        return true;
    }

    @Transactional
    public Boolean deleteUser(Long id) {
        AdminUserDO user = adminUserService.getUser(id);
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        if(CommonStatusEnum.ENABLE.getStatus().equals(user.getStatus())) {
            CustomerDO custCacheByCode = customerService.getCustCacheByCode(user.getUsername());
            if(custCacheByCode != null && custCacheByCode.getCustomerStatus().equals(CommonStatusEnum.ENABLE.getStatus())) {
                throw exception(ErrorCodeConstants.USER_CUSTOMER_STATUS_ENABLE);
            }
        }
        if(user.getStatus().equals(CommonStatusEnum.ENABLE.getStatus())){
            throw exception(ErrorCodeConstants.ACCOUNT_STATUS_ENABLE);
        }
        userRoleService.deleteUserRole(id);
        adminUserService.deleteUser(id);
        return true;
    }
}
